const message = {
  200: 'OK',
  401: 'token已失效',
  '00': '网络错误，请稍后重试',
}

type CodeStatus = 200 | 401 | '00'

const resHandler = () => {
  return async function (ctx, next) {
    ctx.emit = (code: CodeStatus, data?: any, msg?: string) => {
      data = data || {}
      msg = msg || message[code]
      ctx.body = {
        code,
        data,
        msg,
      }
    }

    try {
      await next()
    } catch (error: any) {
      ctx.logger.error(error)
      const { code = '00', data, msg } = error || {}
      ctx.body = {
        code,
        data,
        msg,
      }
    }
  }
}

export default resHandler
